<template>
  <div class="dashboard-container">
    <div class="search">
      <el-row>
        <el-col :span="6">
          <div>
            <el-date-picker
              v-model="months"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="getStoreOrderAmount"
            />
          </div>
        </el-col>
        <el-col :span="18">
          <div style="float:right">
            <el-button @click="totalExport">导出</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div v-if="showDateArray == false">
      <el-table
        :data="monthsArray"
        style="width: 100%"
        show-summary
      >
        <el-table-column
          prop="month"
          label="月份"
        >
          <template slot-scope="scope">
            <div style="color:#2979ff;cursor: pointer" @click="monthData(scope.row.month)">{{ scope.row.month }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="fuiouAmount"
          label="富友收款总额"
        />
        <el-table-column
          prop="fuiouCount"
          label="富友收款笔数"
        />
        <el-table-column
          prop="fuiouWithdraw"
          label="富友提现总额"
        />
        <el-table-column
          prop="fuiouWithdrawing"
          label="富友提现中金额"
        />
        <el-table-column
          prop="huifuAmount"
          label="汇付收款总额"
        />
        <el-table-column
          prop="huifuCount"
          label="汇付收款笔数"
        />
        <el-table-column
          prop="huifuWithdraw"
          label="汇付提现总额"
        />
        <el-table-column
          prop="huifuWithdrawing"
          label="汇付提现中金额"
        />
      </el-table>
    </div>
    <div v-else>
      <el-table
        :data="dateArray"
        style="width: 100%"
        show-summary
      >
        <el-table-column
          label="日期"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.dateStr }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="fuiouAmount"
          label="富友收款总额"
        />
        <el-table-column
          prop="fuiouCount"
          label="富友收款笔数"
        />
        <el-table-column
          prop="fuiouWithdraw"
          label="富友提现总额"
        />
        <el-table-column
          prop="fuiouWithdrawing"
          label="富友提现中金额"
        />
        <el-table-column
          prop="huifuAmount"
          label="汇付收款总额"
        />
        <el-table-column
          prop="huifuCount"
          label="汇付收款笔数"
        />
        <el-table-column
          prop="huifuWithdraw"
          label="汇付提现总额"
        />
        <el-table-column
          prop="huifuWithdrawing"
          label="汇付提现中金额"
        />
        <el-table-column
          label="明细"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.prevent="invoiceDetail(scope.row.dateStr)"
            >
              收款明细
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.native.prevent="withdrawDetail(scope.row.dateStr)"
            >
              提现明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 日收款明细 -->
    <el-dialog
      :title="invoiceTitle"
      :visible.sync="showInvoices"
      width="80%"
    >
      <div>
        <el-table
          :data="invoices"
          style="width: 100%"
        >
          <el-table-column
            prop="createdTime"
            label="支付时间"
          />
          <el-table-column
            prop="amount"
            label="支付金额"
            width="120px"
          />
          <el-table-column
            prop="payment"
            label="渠道"
            width="80px"
          />
          <el-table-column
            prop="gateway"
            label="支付方式"
            width="120px"
          />
          <el-table-column
            prop="outTradeNo"
            label="支付单号"
          />
          <el-table-column
            prop="transactionId"
            label="交易单号"
          />
        </el-table>
      </div>
      <span slot="footer" style="text-align: right">
        <el-button @click="showInvoices = false">取 消</el-button>
        <el-button type="primary" @click="exportInvoices">导 出</el-button>
      </span>
    </el-dialog>

    <!-- 日提现明细 -->
    <el-dialog
      :title="withdrawTitle"
      :visible.sync="showWithdraws"
      width="60%"
    >
      <div>
        <el-table
          :data="withdraws"
          style="width: 100%"
        >
          <el-table-column
            prop="createdTime"
            label="提现时间"
          />
          <el-table-column
            prop="amount"
            label="提现金额"
          />
          <el-table-column
            prop="user"
            label="提现账号"
          />
          <el-table-column
            prop="batchNo"
            label="交易编码"
          />
          <el-table-column
            prop="payment"
            label="提现渠道"
          />
        </el-table>
      </div>
      <span slot="footer" style="text-align: right">
        <el-button @click="showWithdraws = false">取 消</el-button>
        <el-button type="primary" @click="exportWithdraws">导 出</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import exportExcelCsv from '@/utils/exportExcelCsv'
export default {
  data() {
    return {
      months: '',
      monthsArray: [],
      pickerOptions: '',
      amount: 0,
      dateArray: [],
      showDateArray: false,
      invoices: [],
      showInvoices: false,
      invoiceTitle: '收款明细',
      withdraws: [],
      showWithdraws: false,
      withdrawTitle: '提现明细'
    }
  },
  created() {
    this.axios.get(`/manage/invoices`, { params: { '@filter': `entity.getStatus() == 1`, '@select': 'SUM(entity.amount) as amount' }}).then((res) => {
      this.amount = res.data[0].amount
    })
  },
  methods: {
    getStoreOrderAmount() {
      console.log(this.months)
      const startDate = new Date(this.months[0])
      const endDate = new Date(this.months[1])
      const monthsArray = []
      const startYear = startDate.getFullYear()
      const startMonth = startDate.getMonth() + 1
      const endYear = endDate.getFullYear()
      const endMonth = endDate.getMonth() + 1
      for (let y = startYear; y <= endYear; y++) {
        let lastMonth = 12
        let firstMonth = startMonth
        if (y > startYear) {
          firstMonth = 1
        }
        if (y === endYear) {
          lastMonth = endMonth
        }
        for (let m = firstMonth; m <= lastMonth; m++) {
          const month = ` ${y}/${m}`
          const lettleMonths = [4, 6, 9, 11]
          let lastDate = 31
          if (m === 2) {
            if (y % 4 === 0) {
              lastDate = 29
            } else {
              lastDate = 28
            }
          }
          if (lettleMonths.indexOf(m) !== -1) {
            lastDate = 30
          }
          monthsArray.push({
            month: month,
            lastDate: lastDate,
            huifuAmount: 0,
            huifuCount: 0,
            fuiouAmount: 0,
            fuiouCount: 0,
            huifuWithdraw: 0,
            huifuWithdrawing: 0,
            fuiouWithdraw: 0,
            fuiouWithdrawing: 0
          })
        }
      }
      console.log('`12', monthsArray)
      this.monthsArray = monthsArray
      this.getMonthData()
    },
    getMonthData() {
      if (this.monthsArray.length > 0) {
        for (const i of this.monthsArray) {
          this.axios.get(`/manage/invoices`, { params: {
            '@filter': `entity.getStatus() == 1 && entity.getPaidTime() >= datetime.get('${i.month}/01 00:00:00') && entity.getPaidTime() <= datetime.get('${i.month}/${i.lastDate} 23:59:59')`,
            '@select': `SUM(entity.amount) as amount, COUNT(entity.amount) as count, entity.payment as payment`,
            '@groupBy': `entity.payment`
          }}).then((res) => {
            console.log('invoice', res.data)
            for (const j of res.data) {
              if (j.payment.indexOf('fuiou') !== -1) {
                console.log(j.amount)
                i.fuiouAmount += parseFloat(j.amount)
                i.fuiouCount += parseInt(j.count)
              }
              if (j.payment.indexOf('huifu') !== -1) {
                i.huifuAmount += parseFloat(j.amount)
                i.huifuCount += parseInt(j.count)
              }
            }
          })
          this.axios.get(`/manage/withdraws`, { params: {
            '@filter': `entity.getStatus() == 'retrieved' && entity.getCreatedTime() >= datetime.get('${i.month}/01 00:00:00') && entity.getCreatedTime() <= datetime.get('${i.month}/${i.lastDate} 23:59:59')`,
            '@select': `SUM(entity.amount) as amount, entity.payment as payment`,
            '@groupBy': `entity.payment`
          }}).then((res) => {
            console.log('wi', res.data)
            for (const j of res.data) {
              if (j.payment == null || j.payment === '' || j.payment.indexOf('fuiou') !== -1) {
                i.fuiouWithdraw += parseFloat(j.amount)
              }
              if (j.payment.indexOf('huifu') !== -1) {
                i.huifuWithdraw += parseFloat(j.amount)
              }
            }
          })
          this.axios.get(`/manage/withdraws`, { params: {
            '@filter': `entity.getStatus() == 'accepted' && entity.getCreatedTime() >= datetime.get('${i.month}/01 00:00:00') && entity.getCreatedTime() <= datetime.get('${i.month}/${i.lastDate} 23:59:59')`,
            '@select': `SUM(entity.amount) as amount, entity.payment as payment`,
            '@groupBy': `entity.payment`
          }}).then((res) => {
            for (const j of res.data) {
              if (j.payment == null || j.payment === '' || j.payment.indexOf('fuiou') !== -1) {
                i.fuiouWithdrawing += parseFloat(j.amount)
              }
              if (j.payment.indexOf('huifu') !== -1) {
                i.huifuWithdrawing += parseFloat(j.amount)
              }
            }
          })
        }
      }
    },
    // 每日invoice数据
    invoiceDetail(date) {
      console.log(date)
      const loading = this.$loading({
        lock: true,
        text: '数据获取中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.axios.get(`/manage/invoices`, { params: {
        '@filter': `entity.getStatus() == 1 && entity.getCreatedTime() >= datetime.get('${date} 00:00:00') && entity.getCreatedTime() <= datetime.get('${date} 23:59:59')`,
        limit: 10000
      }}).then((res) => {
        if (res.data.length === 0) {
          this.$message.error(`${date}没有收款记录！`)
          loading.close()
        } else {
          console.log('in', res.data)
          this.invoiceTitle = `${date}收款明细`
          const invoices = []
          for (const i of res.data) {
            const date = new Date(i.createdTime)
            const createdTime = this.formatDate(date)
            let payment = '富友'
            if (i.payment.indexOf('huifu') !== -1) {
              payment = '汇付'
            }
            invoices.push({
              createdTime: createdTime,
              amount: i.amount,
              payment: payment,
              gateway: i.gateway,
              outTradeNo: i.outTradeNo,
              transactionId: i.transactionId
            })
          }
          this.invoices = invoices
          this.showInvoices = true
          loading.close()
        }
      })
    },
    // 每日提现明细
    withdrawDetail(date) {
      const loading = this.$loading({
        lock: true,
        text: '数据获取中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.axios.get(`/manage/withdraws`, { params: {
        '@filter': `entity.getStatus() == 'retrieved' && entity.getCreatedTime() >= datetime.get('${date} 00:00:00') && entity.getCreatedTime() <= datetime.get('${date} 23:59:59')`,
        limit: 10000
      }}).then((res) => {
        if (res.data.length === 0) {
          this.$message.error(`${date}没有提现成功记录！`)
          loading.close()
        } else {
          console.log('w', res.data)
          this.withdrawTitle = `${date}提现明细`
          const withdraws = []
          for (const i of res.data) {
            const date = new Date(i.createdTime)
            const createdTime = this.formatDate(date)
            let payment = '富友'
            if (i.payment !== null && i.payment !== '' && i.payment.indexOf('huifu') !== -1) {
              payment = '汇付'
            }
            withdraws.push({
              createdTime: createdTime,
              amount: i.amount,
              user: i.user.__toString,
              batchNo: i.batchNo,
              payment: payment
            })
          }
          console.log('width', withdraws)
          this.withdraws = withdraws
          this.showWithdraws = true
          loading.close()
        }
      })
    },
    // 月份的每日数据
    monthData(month) {
      this.dateArray = []
      const yearMonth = month.split('/')
      const days = new Date(yearMonth[0], yearMonth[1], 0).getDate()
      for (let i = 1; i <= days; i++) {
        this.dateArray.push({
          dateStr: `${month}/${i}`,
          huifuAmount: 0,
          huifuCount: 0,
          fuiouAmount: 0,
          fuiouCount: 0,
          huifuWithdraw: 0,
          huifuWithdrawing: 0,
          fuiouWithdraw: 0,
          fuiouWithdrawing: 0
        })
      }
      console.log(this.dateArray)
      this.showDateArray = true
      for (const i of this.dateArray) {
        this.axios.get(`/manage/invoices`, { params: {
          '@filter': `entity.getStatus() == 1 && entity.getCreatedTime() >= datetime.get('${i.dateStr} 00:00:00') && entity.getCreatedTime() <= datetime.get('${i.dateStr} 23:59:59')`,
          '@select': `SUM(entity.amount) as amount, COUNT(entity.amount) as count, entity.payment as payment`,
          '@groupBy': `entity.payment`
        }}).then((res) => {
          for (const j of res.data) {
            if (j.payment.indexOf('fuiou') !== -1) {
              console.log(j.amount)
              i.fuiouAmount += parseFloat(j.amount)
              i.fuiouCount += parseInt(j.count)
            }
            if (j.payment.indexOf('huifu') !== -1) {
              i.huifuAmount += parseFloat(j.amount)
              i.huifuCount += parseInt(j.count)
            }
          }
        })
        this.axios.get(`/manage/withdraws`, { params: {
          '@filter': `entity.getStatus() == 'retrieved' && entity.getCreatedTime() >= datetime.get('${i.dateStr} 00:00:00') && entity.getCreatedTime() <= datetime.get('${i.dateStr} 23:59:59')`,
          '@select': `SUM(entity.amount) as amount, entity.payment as payment`,
          '@groupBy': `entity.payment`
        }}).then((res) => {
          for (const j of res.data) {
            if (j.payment == null || j.payment === '' || j.payment.indexOf('fuiou') !== -1) {
              i.fuiouWithdraw += parseFloat(j.amount)
            }
            if (j.payment.indexOf('huifu') !== -1) {
              i.huifuWithdraw += parseFloat(j.amount)
            }
          }
        })
        this.axios.get(`/manage/withdraws`, { params: {
          '@filter': `entity.getStatus() == 'accepted' && entity.getCreatedTime() >= datetime.get('${i.dateStr} 00:00:00') && entity.getCreatedTime() <= datetime.get('${i.dateStr} 23:59:59')`,
          '@select': `SUM(entity.amount) as amount, entity.payment as payment`,
          '@groupBy': `entity.payment`
        }}).then((res) => {
          for (const j of res.data) {
            if (j.payment == null || j.payment === '' || j.payment.indexOf('fuiou') !== -1) {
              i.fuiouWithdraw += parseFloat(j.amount)
            }
            if (j.payment.indexOf('huifu') !== -1) {
              i.huifuWithdraw += parseFloat(j.amount)
            }
          }
        })
      }
    },
    exportInvoices() {
      const label = {
        'createdTime': '支付时间',
        'amount': '支付金额',
        'payment': '渠道',
        'gateway': '支付方式',
        'outTradeNo': '支付单号',
        'transactionId': '交易单号'
      }
      const list = JSON.parse(JSON.stringify(this.invoices))
      exportExcelCsv(label, list, `${this.invoiceTitle}.csv`)
    },
    exportWithdraws() {
      const label = {
        'createdTime': '提现时间',
        'amount': '提现金额',
        'user': '提现账号',
        'batchNo': '交易编号',
        'payment': '提现渠道'
      }
      const list = JSON.parse(JSON.stringify(this.withdraws))
      exportExcelCsv(label, list, `${this.withdrawTitle}.csv`)
    },
    totalExport() {
      let label = {
        'month': '月份',
        'fuiouAmount': '富友收款金额',
        'fuiouCount': '富友收款单数',
        'fuiouWithdraw': '富友提现金额',
        'fuiouWithdrawing': '富友提现中金额',
        'huifuAmount': '汇付收款金额',
        'huifuCount': '汇付收款单数',
        'huifuWithdraw': '汇付提现金额',
        'huifuWithdrawing': '汇付提现中金额'
      }
      let list = []
      // table数据
      if (this.showDateArray === false) {
        list = JSON.parse(JSON.stringify(this.monthsArray))
        if (list.length === 0) {
          this.$message.error('暂无导出数据')
          return
        }
      } else {
        list = JSON.parse(JSON.stringify(this.dateArray))
        if (list.length === 0) {
          this.$message.error('暂无导出数据')
          return
        }
        label = {
          'dateStr': '日期',
          'amount': '收入',
          'count': '支付单数',
          'withdraw': '提现金额',
          'withdrawing': '提现中金额'
        }
      }
      exportExcelCsv(label, list, `报表.csv`)
    },
    formatDate(date) {
      var year = date.getFullYear()
      var month = ('0' + (date.getMonth() + 1)).slice(-2)
      var day = ('0' + date.getDate()).slice(-2)
      var hours = ('0' + date.getHours()).slice(-2)
      var minutes = ('0' + date.getMinutes()).slice(-2)
      var seconds = ('0' + date.getSeconds()).slice(-2)
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.search{
  padding:10px;
}

.deposit{
  padding: 20px 0px;
  margin: 5px 10px;
  background-color: #2979ff;
  color: #fff;
  font-size:24px;
  border-radius: 5px;
  text-align: center;
}
</style>
